package com.icinfo.cloud.provider.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.icinfo.framework.tools.utils.HttpClientUtil;
import io.micrometer.core.instrument.util.IOUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Http请求工具封装.
 */
public class HttpUtils extends HttpClientUtil {


    /**
     * 判断是否Ajax请求
     *
     * @param request 请求/CaseMainInfoDto.java
     * @return ajax请求：true 否则 false
     */
    public static boolean isAjax(HttpServletRequest request) {
        // 判定是否为异步请求，非异步请求直接进入error页面
        return ((request.getHeader("accept") != null && request.getHeader("accept").indexOf("application/json") > -1)
                || (request.getHeader("X-Requested-With") != null
                && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1));
    }

    /**
     * 异步请求异常处理
     *
     * @param response   请求响应
     * @param errorInfo  错误信息
     * @param httpStatus http状态码
     * @throws Exception
     */
    public static void writeError(HttpServletResponse response, String errorInfo, int httpStatus) throws Exception {
        PrintWriter writer = null;
        try {
            // 设置响应字符集
            response.setContentType("text/html; charset=utf-8");
            // 设置HTTP响应状态码
            response.setStatus(httpStatus);
            writer = response.getWriter();
            writer.write(errorInfo);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }


    public static String doHttpPost(String url, Map<String, Object> paraMap) throws Exception {
        String msgRet = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //访问归结接口
        HttpPost post = new HttpPost(url);
        try {
            // 请求类型：x-www-form-urlencoded
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for (String key : paraMap.keySet()) {
                nvps.add(new BasicNameValuePair(key, paraMap.get(key).toString()));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
                    nvps, Consts.UTF_8);
            entity.setContentEncoding("UTF-8");
            entity.setContentType(ContentType.APPLICATION_FORM_URLENCODED
                    .getMimeType());
            post.setEntity(entity);
            RequestConfig requestConfig=RequestConfig.custom().setConnectTimeout(3000).setSocketTimeout(3000).setConnectionRequestTimeout(3000).build();
            post.setConfig(requestConfig);
            msgRet = EntityUtils.toString(httpClient.execute(post).getEntity(), "UTF-8");
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        } finally {
            httpClient.close();
        }
        return msgRet;
    }

    public static String doHttpPostWithToken(String url, String token, Map<String, Object> paraMap) throws Exception {
        String msgRet = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //访问接口
        HttpPost post = new HttpPost(url);
        try {
            post.addHeader("Authorization", token);
            // 请求类型：application/json
            StringEntity entity = new StringEntity(
                    new ObjectMapper().writeValueAsString(paraMap),
                    Consts.UTF_8);
            entity.setContentEncoding("UTF-8");
            entity.setContentType(ContentType.APPLICATION_JSON
                    .getMimeType());
            post.setEntity(entity);
            msgRet = EntityUtils.toString(httpClient.execute(post).getEntity(), "UTF-8");
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        } finally {
            httpClient.close();
        }
        return msgRet;
    }

    /**
     * 传送json类型的post请求
     *
     * @param url
     * @param json
     * @return String
     */
    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * 传送json类型的post请求
     *
     * @param url
     * @param json
     * @return String
     */
    public static String doPostJsonHttps(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            //使用 loadTrustMaterial() 方法实现一个信任策略，信任所有证书
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 信任所有
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            //NoopHostnameVerifier类:  作为主机名验证工具，实质上关闭了主机名验证，它接受任何
            //有效的SSL会话并匹配到目标主机。
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
    /**
     *get请求包含请求头信息
     * @author liyafeng
     * @date 2022/7/6
      * @param url
     * @param paramMap
     * @param headerMap
     * @return {@link JSONObject}
     */
    public static String  doGet(String url, Map<String, String> paramMap, Map<String, String> headerMap) {
        String  result = "";
        // 获取连接客户端工具
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            /*
             * 由于GET请求的参数都是拼装在URL地址后方，所以我们要构建一个URL，带参数
             */
            URIBuilder uriBuilder = new URIBuilder(url);

            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                uriBuilder.addParameter(entry.getKey(), entry.getValue());
            }

            //拼接请求头参数
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                httpGet.setHeader(entry.getKey(), entry.getValue());
            }
            // 执行请求
            response = httpClient.execute(httpGet);
            // 获得响应的实体对象
            HttpEntity entity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            if (entity != null) {
                // 将返回结果处理成String对象
                result = EntityUtils.toString(entity, "UTF-8");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放连接
            if (null != response) {
                try {
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    System.err.println("释放连接出错");
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
    public static JSONObject doHttpPostWithHeader(String url, Map<String, String> paraMap,Map<String,String> headerMap) throws Exception {
        JSONObject jsonObject = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //访问接口
        HttpPost post = new HttpPost(url);
        try {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
            // 请求类型：application/json
            StringEntity entity = new StringEntity(
                    new ObjectMapper().writeValueAsString(paraMap),
                    Consts.UTF_8);
            entity.setContentEncoding("UTF-8");
            entity.setContentType(ContentType.APPLICATION_JSON
                    .getMimeType());
            post.setEntity(entity);
            String result = EntityUtils.toString(httpClient.execute(post).getEntity(), "UTF-8");
            jsonObject=com.alibaba.fastjson.JSON.parseObject(result);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        } finally {
            httpClient.close();
        }
        return jsonObject;
    }

    /**
     * 发送 GET 请求（HTTP），K-V形式
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static String doGet(String url, Map<String, String> params) throws IOException {
        int i = 0;
        if (params != null) {
            StringBuffer param = new StringBuffer();
            for (String key : params.keySet()) {
                if (i == 0)
                    param.append("?");
                else
                    param.append("&");
                param.append(key).append("=").append(params.get(key));
                i++;
            }
            url += param;
        }
        String result = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            response = httpclient.execute(httpGet);
            // int statusCode = response.getStatusLine().getStatusCode();

            entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                result = IOUtils.toString(instream, StandardCharsets.UTF_8);
            }
        } finally {
            // 最后别忘了关闭应该关闭的资源，适当的释放资源
            try {
                // 这个方法也可以把底层的流给关闭了
                EntityUtils.consume(entity);
                // if (null != response) {
                // response.close();
                // }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}

